<template>
  <el-dialog v-model="show" :title="diaLog ? '编辑' : '新增'" width="30%">
    <el-form ref="ruleFormRef" :model="fromData" :rules="rules" label-width="120px" status-icon>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="fromData.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="fromData.password" />
      </el-form-item>
      <div v-if="diaLog">
        <el-form-item label="头像" prop="avator">
          <el-input v-model="fromData.avator" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="fromData.nickname" />
        </el-form-item>
        <el-form-item label="id" prop="id">
          <el-input v-model="fromData.id" />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelHandler">取消</el-button>
        <el-button type="primary" @click="confirmHandler">
          {{ diaLog ? '保存' : '添加' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { reactive, ref } from 'vue';
const show = defineModel({ required: true })
const props = defineProps(['diaLog'])
const emits = defineEmits(['add', 'edit'])
const fromData = reactive({
  username: "",
  password: "",
  avator: "",
  nickname: "",
  id: ""
})
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度为3~20', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度为3~20', trigger: 'blur' },
  ],
})
// 更新时控制数据是否回显
onUpdated(() => {
  if (props.diaLog) {
    Object.assign(fromData, props.diaLog)
  } else {
    for (var key in fromData) {
      fromData[key] = ""
    }
  }
})
// 关闭对话框时
function cancelHandler() {
  fromData.username = ""
  fromData.password = ""
  fromData.avator = ""
  fromData.nickname = ""
  fromData.id = ""
  show.value = false
}
// 确认按钮
function confirmHandler() {
  if (props.diaLog) {
    emits('edit', { ...fromData, id: props.diaLog.id })
  } else {
    emits('add', fromData)
  }
  cancelHandler()
}
</script>
<style scoped></style>
